package com.example.pt.controller;

import com.auth0.jwt.interfaces.DecodedJWT;
import com.example.pt.entity.Invitation;
import com.example.pt.entity.User;
import com.example.pt.entity.UserLevel;
import com.example.pt.repository.InvitationRepositories;
import com.example.pt.service.InvitationService;
import com.example.pt.service.UserLevelService;
import com.example.pt.service.UserService;
import com.example.pt.utils.JWTUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 邀请码控制器
 */
@RestController
@RequestMapping("/api/invitation")
@CrossOrigin
public class InvitationController {
    
    @Autowired
    private InvitationService invitationService;
    
    @Autowired
    private UserService userService;
    
    @Autowired
    private UserLevelService userLevelService;
    
    @Autowired
    private InvitationRepositories invitationRepositories;
    
    /**
     * 验证邀请码有效性
     * @param code 邀请码
     * @return 验证结果
     */
    @GetMapping("/verify/{code}")
    public ResponseEntity<?> verifyInvitationCode(@PathVariable String code) {
        if (code == null || code.isEmpty()) {
            return ResponseEntity.badRequest().body("邀请码不能为空");
        }
        
        Invitation invitation = invitationRepositories.findByInvitationCode(code);
        
        if (invitation == null) {
            return ResponseEntity.ok(Map.of("valid", false, "message", "邀请码不存在"));
        }
        
        boolean isValid = invitation.isValid();
        String message = isValid ? "邀请码有效" : "邀请码已失效";
        
        Map<String, Object> response = new HashMap<>();
        response.put("valid", isValid);
        response.put("message", message);
        
        // 添加已使用次数信息
        int usedCount = invitation.getInvitationNumber() == null ? 0 : invitation.getInvitationNumber();
        response.put("usedCount", usedCount);
        response.put("maxUses", 3);
        response.put("remainingUses", 3 - usedCount);
        
        if (isValid) {
            User inviter = userService.searchByUid(invitation.getUid());
            if (inviter != null) {
                response.put("inviter", inviter.getUsername());
            }
        }
        
        return ResponseEntity.ok(response);
    }
    
    /**
     * 获取用户的邀请码列表
     * @return 邀请码列表
     */
    @GetMapping("/user")
    public ResponseEntity<?> getUserInvitations(@RequestHeader Map<String, String> headers) {
        String token = headers.get("token");
        if (token == null) {
            token = headers.get("authorization");
            if (token != null && token.startsWith("Bearer ")) {
                token = token.substring(7);
            }
        }
        
        if (token == null) {
            Map<String, Object> response = new HashMap<>();
            response.put("message", "未登录: 缺少token");
            response.put("status", "error");
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(response);
        }
        
        try {
            DecodedJWT jwt = JWTUtil.verifyToken(token);
            Integer userId = jwt.getClaim("uid").asInt();
            
            User user = userService.searchByUid(userId);
            if (user == null) {
                return ResponseEntity.notFound().build();
            }

            userLevelService.updateUserLevel(userId);
            
            // 获取用户所有邀请码
            List<Invitation> invitations = invitationRepositories.findAll().stream()
                    .filter(inv -> inv.getUid().equals(userId))
                    .collect(Collectors.toList());
            
            // 邀请码使用情况统计
            long totalCount = invitations.size();
            
            // 根据新的规则统计
            long fullyUsedCount = invitations.stream()
                    .filter(inv -> inv.getInvitationNumber() != null && inv.getInvitationNumber() >= 3)
                    .count();
            
            long partiallyUsedCount = invitations.stream()
                    .filter(inv -> inv.getInvitationNumber() != null && inv.getInvitationNumber() > 0 && inv.getInvitationNumber() < 3)
                    .count();
            
            long expiredCount = invitations.stream()
                    .filter(inv -> inv.getStatus() != null && inv.getStatus() == 2)
                    .count();
            
            long validCount = invitations.stream()
                    .filter(Invitation::isValid)
                    .count();
            
            // 添加每个邀请码的剩余使用次数
            List<Map<String, Object>> invitationDetails = invitations.stream()
                    .map(inv -> {
                        Map<String, Object> details = new HashMap<>();
                        details.put("id", inv.getId());
                        details.put("code", inv.getInvitationCode());
                        details.put("createTime", inv.getCreateTime());
                        details.put("expireTime", inv.getExpireTime());
                        details.put("status", inv.getStatus());
                        
                        int usedCount = inv.getInvitationNumber() == null ? 0 : inv.getInvitationNumber();
                        details.put("usedCount", usedCount);
                        details.put("remainingUses", 3 - usedCount);
                        details.put("isValid", inv.isValid());
                        
                        return details;
                    })
                    .collect(Collectors.toList());
            
            Map<String, Object> response = new HashMap<>();
            response.put("userId", userId);
            response.put("username", user.getUsername());
            response.put("totalCount", totalCount);
            response.put("fullyUsedCount", fullyUsedCount);
            response.put("partiallyUsedCount", partiallyUsedCount);
            response.put("expiredCount", expiredCount);
            response.put("validCount", validCount);
            response.put("invitations", invitationDetails);
            response.put("status", "success");

            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<>();
            response.put("message", "未登录: " + e.getMessage());
            response.put("status", "error");
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(response);
        }
    }
    
    /**
     * 注册用户使用邀请码
     * @param userId 新用户ID
     * @param invitationCode 邀请码
     * @return 使用结果
     */
    @PostMapping("/register")
    public ResponseEntity<?> registerWithInvitation(@RequestParam Integer userId, @RequestParam String invitationCode) {
        if (userId == null || invitationCode == null || invitationCode.isEmpty()) {
            return ResponseEntity.badRequest().body("用户ID和邀请码不能为空");
        }
        
        boolean success = userLevelService.rewardNewUserWithInvitation(userId, invitationCode);
        
        if (success) {
            // 获取新用户信息
            User user = userService.searchByUid(userId);
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("userId", userId);
            response.put("username", user.getUsername());
            response.put("points", user.getPoints());
            response.put("message", "邀请码使用成功，获得100积分奖励");
            
            return ResponseEntity.ok(response);
        } else {
            return ResponseEntity.badRequest().body(Map.of(
                "success", false,
                "message", "邀请码无效或已使用"
            ));
        }
    }
} 